<?php

namespace App\Console\Commands\WorkOrder;

use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Models\WorkOrder\WorkOrderGatherModel;
use Illuminate\Console\Command;

class WorkOrderGatherCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'workOrder:work_order_gather';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '一次性脚本 工单数据汇总';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 同步所有工单号
        WorkOrderApplyMainModel::query()
            ->where('sourceType', WorkOrderApplyMainModel::SOURCE_TYPE_0)
            ->chunkById(200, function ($orders) {
                $gatherData = [];
                foreach ($orders as $order) {
                    $gatherData[] = [
                        'workOrderNo' => $order->workOrderNo,
                        'shopId'      => $order->shopId,
                        'createdAt'   => $order->createdAt->timestamp,
                        'updatedAt'   => $order->updatedAt->timestamp,
                    ];
                }

                // 同步工单
                if (count($gatherData)) {
                    WorkOrderGatherModel::query()->insert($gatherData);
                }
            });
    }
}
